package com.ayf.payment.game.api.controller.paychannel;

import com.alibaba.fastjson.JSON;
import com.ayf.payment.game.api.channel.alipay.service.AliPayService;
import com.ayf.payment.game.api.dto.alipay.CallbackForm;
import com.ayf.payment.game.api.utils.HttpServletRequestUtil;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 支付宝代付异步通知
 * @Author: zh-liang
 * @Date : 2020-07-17 11:52
 */
@RestController
public class AliPayNotifyController {
    @Autowired
    private AliPayService aliPayService;

    @RequestMapping(value = "/zfb/singlePayTrade/notify")
    public ResponseEntity AliCallback(HttpServletRequest request) {
        String logkey = "支付宝官方单笔代付后台异步通知";
        LogPortal.info("{} received request", logkey);
        boolean callback = false;
        CallbackForm form = new CallbackForm();
        try {
            form.setHeaders(HttpServletRequestUtil.getHeadersInfo(request));
            form.setParameters(HttpServletRequestUtil.getRequestParameters(request));
            LogPortal.info("{} request form:{}", logkey, JSON.toJSON(form));
            callback = check(form);
        } catch (Exception e) {
            LogPortal.error("{} 失败", e, logkey);
        }
        String result = "fail";
        if (callback) {
            result = "success";
        }
        LogPortal.info("{} 我方验签以及处理结果:{}，我方返回{}", logkey, callback, result);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    private boolean check(CallbackForm form) {
        return aliPayService.callback(form);
    }
}
